'use strict'

const { Controller } = require('egg')

class HomeController extends Controller {
  // 获取用户列表
  async index() {
    const { ctx, service } = this
    await ctx.isAdmin()
    ctx.body = await service.user.list()
  }

  // 更新用户
  async update() {
    const { ctx, service } = this
    await ctx.validateId()
    const stream = await service.user.update()
    if (!stream) {
      ctx.throw(404, 'not found', '用户不存在')
    }
    ctx.body = stream
  }

  // 删除用户
  async destroy() {
    const { ctx, service } = this
    await ctx.isAdmin()
    await ctx.validateId()
    const user = await ctx.model.User.findById(ctx.params.id)
    if (!user) {
      ctx.throw(404, 'not found', '对象不存在')
    }
    if (user._id.toString() === ctx.user._id.toString()) {
      ctx.throw(403, 'not permission', '不能删除自己')
    }
    ctx.body = await user.remove()
  }

  async login() {
    const { ctx, service } = this
    const { name, password, remember } = ctx.request.body
    ctx.validate({
      name: [{ required: true, message: '请输入用户名' }],
      password: [{ required: true, message: '请输入密码' }],
    })
    const user = await ctx.model.User.findOne({ $or: [{ name }, { email: name }] })
    if (!user) {
      ctx.throw(404, 'not found', '用户不存在')
    }
    if (user.password !== ctx.helper.encrypt(password)) {
      ctx.throw(422, 'not validate', '密码错误')
    }
    // 分配 uuid
    const now = Date.now()
    const expiredAt = remember ? Math.floor(7 * 1000 * 86400 + now) : Math.floor(4000 * 3600 + now)
    user.session = `${user._id}__${require('node-uuid').v4()}__${expiredAt}`
    await user.save()
    user.password = user.session
    const data = user.toObject()
    const { title, host, port } = require('../../config/config')
    Object.assign(data, { title, host, port })
    ctx.body = data
  }

  async register() {
    const { ctx, service } = this
    let { name, password, email } = ctx.request.body
    ctx.validate({
      name: [{ required: true, message: '请输入用户名' }],
      password: [{ required: true, message: '请输入密码' }],
    })
    if (await ctx.model.User.findOne({ $or: [{ name, email }] })) {
      ctx.throw(422, 'not validate', '用户名或邮箱已注册')
    }
    // 加密
    password = ctx.helper.encrypt(password)
    const user = ctx.model.User.create({
      name,
      password,
      email,
    })
    delete user.password
    ctx.body = await user
  }

  async changePassword() {
    const { ctx, service } = this
    const _id = ctx.params.id
    const { password, newPassword } = ctx.request.body
    if (!password || !newPassword) {
      ctx.throw(422, 'not validate', '请输入密码')
    }
    const user = await ctx.model.User.findById(_id)
    if (!user) {
      ctx.throw(404, 'not found', '用户不存在')
    }
    if (user.password !== ctx.helper.encrypt(password)) {
      ctx.throw(422, 'not validate', '原密码错误')
    }
    user.password = ctx.helper.encrypt(newPassword)
    await user.save()
    ctx.body = {}
  }
}

module.exports = HomeController
